//
//  PictureSelectorViewController.swift
//  微博分支添加图片
//
//  Created by JJ on 15/9/10.
//  Copyright © 2015年 JJ. All rights reserved.
//

import UIKit

private let PictureSelectorCellID = "PictureSelectorCellID"
private let maxImageCount = 9
class PictureSelectorViewController: UICollectionViewController,PictureSelectorCellDelegate{
    
    lazy var pictures = [UIImage]()
    private var currentIndex = 0
    
    init(){
        
        let layout=UICollectionViewFlowLayout()
        super.init(collectionViewLayout: layout)
        layout.itemSize=CGSize(width: 80, height: 80)
        layout.sectionInset=UIEdgeInsetsMake(10, 10, 10, 10)

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        collectionView?.backgroundColor=UIColor(white: 0.97, alpha: 1.0)
       
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: PictureSelectorCellID)
        

    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictures.count + (pictures.count == maxImageCount ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureSelectorCellID, forIndexPath: indexPath) as! PictureSelectorCell
 
        cell.pictureDelegate=self
        cell.image=indexPath.item < pictures.count ? pictures[indexPath.item]:nil
        print(pictures.count)
        return cell
    }
    
    private func pictureSelectorCellClickRemoveButton(cell: PictureSelectorCell) {
        
        if let indexPath=collectionView?.indexPathForCell(cell)  where indexPath.item < pictures.count{
            pictures.removeAtIndex(indexPath.item)
            collectionView?.reloadData()
        }
      
    }
    
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            return
        }
        print(indexPath.item)
        
        currentIndex=indexPath.item
        let picker=UIImagePickerController()
        
        presentViewController(picker, animated: true, completion: nil)
        picker.delegate = self
    }
    
    
}

extension PictureSelectorViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage=image.scaleImageToWidth(300)
        if currentIndex < pictures.count{
            pictures[currentIndex]=scaleImage
        }else{
            pictures.append(scaleImage)
        }
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}



    /// 自定义cell

private protocol PictureSelectorCellDelegate:NSObjectProtocol{
    
    func pictureSelectorCellClickRemoveButton(cell:PictureSelectorCell)
}

    private class PictureSelectorCell:UICollectionViewCell {
        
      weak var pictureDelegate:PictureSelectorCellDelegate?
        
        var image:UIImage?{
            didSet{
                if image==nil{
                    picturebutton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
                }else{
                
                    picturebutton.setImage(image, forState: .Normal)
                }
                removeButton.hidden = image == nil
            }
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            setUI()
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        @objc private func clickRemove(){
            
            pictureDelegate?.pictureSelectorCellClickRemoveButton(self)
        }
        
        private func setUI(){
            
            contentView.addSubview(picturebutton)
            contentView.addSubview(removeButton)
            
            picturebutton.frame=bounds
            
            removeButton.translatesAutoresizingMaskIntoConstraints=false
            let viewDic=["btn":removeButton]
            contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[btn]-0-|", options: [], metrics: nil, views: viewDic))
            contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[btn]", options: [], metrics: nil, views: viewDic))
            
            picturebutton.userInteractionEnabled=false
            removeButton.addTarget(self, action: "clickRemove", forControlEvents: UIControlEvents.TouchUpInside)
            picturebutton.imageView?.contentMode=UIViewContentMode.ScaleAspectFill
        }
        
        private lazy var picturebutton:UIButton = UIButton(imageName: "compose_pic_add")
        
        private lazy var removeButton:UIButton = UIButton(imageName: "compose_photo_close")
        
}










